import api from '@/utils/api'

const state = {
  jobList: [],
  jobDetail: null,
  searchParams: {
    keyword: '',
    city: '',
    salaryRange: '',
    experience: '',
    education: '',
    jobType: '',
    page: 1,
    size: 20
  },
  // 新增的状态
  searchState: {
    selectedSkills: ['Python', 'Java'],
    currentSkill: 'Python',
    searchKeyword: ''
  },
  filterState: {
    filterType: 'recommend', // recommend, nearby, latest
    selectedCity: '武汉',
    advancedFilters: {
      salaryMin: null,
      salaryMax: null,
      companySize: '',
      workType: '' // 全职/实习/兼职
    }
  },
  userPreferences: {
    defaultCity: '武汉',
    frequentSkills: ['Python', 'Java', 'JavaScript'],
    recentSearches: []
  },
  categoryList: [],
  cityList: [],
  hotJobs: []
}

const mutations = {
  SET_JOB_LIST(state, { list, isRefresh = false }) {
    if (isRefresh) {
      state.jobList = list
    } else {
      state.jobList = [...state.jobList, ...list]
    }
  },
  
  SET_JOB_DETAIL(state, jobDetail) {
    state.jobDetail = jobDetail
  },
  
  SET_SEARCH_PARAMS(state, params) {
    state.searchParams = { ...state.searchParams, ...params }
  },
  
  SET_CATEGORY_LIST(state, categoryList) {
    state.categoryList = categoryList
  },
  
  SET_CITY_LIST(state, cityList) {
    state.cityList = cityList
  },
  
  SET_HOT_JOBS(state, hotJobs) {
    state.hotJobs = hotJobs
  },
  
  RESET_SEARCH_PARAMS(state) {
    state.searchParams = {
      keyword: '',
      city: '',
      salaryRange: '',
      experience: '',
      education: '',
      jobType: '',
      page: 1,
      size: 20
    }
  },
  
  // 新增的 mutations
  SET_SEARCH_STATE(state, searchState) {
    state.searchState = { ...state.searchState, ...searchState }
  },
  
  SET_FILTER_STATE(state, filterState) {
    state.filterState = { ...state.filterState, ...filterState }
  },
  
  SET_USER_PREFERENCES(state, preferences) {
    state.userPreferences = { ...state.userPreferences, ...preferences }
  },
  
  ADD_RECENT_SEARCH(state, searchTerm) {
    const recentSearches = state.userPreferences.recentSearches
    const index = recentSearches.indexOf(searchTerm)
    
    if (index > -1) {
      recentSearches.splice(index, 1)
    }
    
    recentSearches.unshift(searchTerm)
    
    // 保持最近10条记录
    if (recentSearches.length > 10) {
      recentSearches.pop()
    }
  }
}

const actions = {
  // 获取职位列表
  async getJobList({ commit, state }, { isRefresh = false } = {}) {
    try {
      if (isRefresh) {
        commit('SET_SEARCH_PARAMS', { page: 1 })
      }
      
      const response = await api.get('/jobs', {
        params: state.searchParams
      })
      
      commit('SET_JOB_LIST', { 
        list: response.data.list || [], 
        isRefresh 
      })
      
      // 如果不是刷新，增加页码
      if (!isRefresh) {
        commit('SET_SEARCH_PARAMS', { 
          page: state.searchParams.page + 1 
        })
      }
      
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 获取职位详情
  async getJobDetail({ commit }, jobId) {
    try {
      const response = await api.get(`/jobs/${jobId}`)
      commit('SET_JOB_DETAIL', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 搜索职位
  async searchJobs({ commit, dispatch }, searchParams) {
    commit('SET_SEARCH_PARAMS', searchParams)
    return await dispatch('getJobList', { isRefresh: true })
  },
  
  // 获取职位分类
  async getJobCategories({ commit }) {
    try {
      const response = await api.get('/jobs/categories')
      commit('SET_CATEGORY_LIST', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 获取城市列表
  async getCityList({ commit }) {
    try {
      const response = await api.get('/common/cities')
      commit('SET_CITY_LIST', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 获取热门职位
  async getHotJobs({ commit }) {
    try {
      const response = await api.get('/jobs/hot')
      commit('SET_HOT_JOBS', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 投递简历
  async applyJob({ commit }, { jobId, resumeId, coverLetter }) {
    try {
      const response = await api.post('/applications', {
        jobId,
        resumeId,
        coverLetter
      })
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 收藏职位
  async favoriteJob({ commit }, jobId) {
    try {
      const response = await api.post(`/jobs/${jobId}/favorite`)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 取消收藏
  async unfavoriteJob({ commit }, jobId) {
    try {
      const response = await api.delete(`/jobs/${jobId}/favorite`)
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 新增的 actions
  updateSearchState({ commit }, searchState) {
    commit('SET_SEARCH_STATE', searchState)
  },
  
  updateFilterState({ commit }, filterState) {
    commit('SET_FILTER_STATE', filterState)
  },
  
  updateUserPreferences({ commit }, preferences) {
    commit('SET_USER_PREFERENCES', preferences)
    // 持久化存储到本地
    try {
      uni.setStorageSync('userPreferences', preferences)
    } catch (error) {
      console.error('保存用户偏好失败:', error)
    }
  },
  
  loadUserPreferences({ commit }) {
    try {
      const preferences = uni.getStorageSync('userPreferences')
      if (preferences) {
        commit('SET_USER_PREFERENCES', preferences)
      }
    } catch (error) {
      console.error('加载用户偏好失败:', error)
    }
  },
  
  addRecentSearch({ commit }, searchTerm) {
    if (searchTerm && searchTerm.trim()) {
      commit('ADD_RECENT_SEARCH', searchTerm.trim())
    }
  },
  
  // 根据技能搜索职位
  async searchJobsBySkill({ commit, dispatch }, skill) {
    try {
      commit('SET_SEARCH_STATE', { currentSkill: skill })
      const response = await api.job.searchBySkill(skill)
      commit('SET_JOB_LIST', { list: response.data.list || [], isRefresh: true })
      return response
    } catch (error) {
      throw error
    }
  },
  
  // 根据筛选类型搜索
  async searchJobsByFilter({ commit, dispatch }, filterType) {
    try {
      commit('SET_FILTER_STATE', { filterType })
      let response
      
      switch (filterType) {
        case 'recommend':
          response = await api.job.getRecommendJobs()
          break
        case 'nearby':
          // TODO: 获取地理位置
          response = await api.job.getNearbyJobs(30.5928, 114.3055) // 武汉坐标
          break
        case 'latest':
          response = await api.job.getLatestJobs()
          break
        default:
          response = await api.job.getHotJobs()
      }
      
      commit('SET_JOB_LIST', { list: response.data.list || response.data || [], isRefresh: true })
      return response
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  jobList: state => state.jobList,
  jobDetail: state => state.jobDetail,
  searchParams: state => state.searchParams,
  categoryList: state => state.categoryList,
  cityList: state => state.cityList,
  hotJobs: state => state.hotJobs,
  // 新增的 getters
  searchState: state => state.searchState,
  filterState: state => state.filterState,
  userPreferences: state => state.userPreferences,
  selectedSkills: state => state.searchState.selectedSkills,
  currentSkill: state => state.searchState.currentSkill,
  filterType: state => state.filterState.filterType,
  selectedCity: state => state.filterState.selectedCity,
  recentSearches: state => state.userPreferences.recentSearches
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}